<template>
	<div class="system-user-container layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<div class="system-user-search mb15">
				<el-input size="default" v-model="state.queryParams.realName" placeholder="请输入用户名称" style="max-width: 180px"> </el-input>
				<el-button size="default" type="primary" class="ml10" @click="handleQuery">
					<el-icon>
						<ele-Search />
					</el-icon>
					查询
				</el-button>
				<el-button size="default" type="success" class="ml10" @click="onOpenAddUser('add')">
					<el-icon>
						<ele-FolderAdd />
					</el-icon>
					新增用户
				</el-button>
			</div>
			<el-table :data="state.userData" v-loading="state.loading" style="width: 100%">
				<el-table-column type="index" label="序号" width="60" />
				<el-table-column prop="account" label="账号" show-overflow-tooltip></el-table-column>
				<el-table-column prop="nickName" label="昵称" show-overflow-tooltip></el-table-column>
				<el-table-column prop="realName" label="姓名" width="120" align="center" show-overflow-tooltip />
				<el-table-column prop="orderNo" label="排序" show-overflow-tooltip></el-table-column>
				<el-table-column prop="orgId" label="orgId" show-overflow-tooltip></el-table-column>
				<el-table-column prop="orgId" label="所属单位" align="center" :formatter="dictFormatter" show-overflow-tooltip="">
					<template #default="scope">
					<div style="display: flex; align-items: center">
						{{ dictFormatter(scope.row.orgId) }}
					</div>
					</template>
				</el-table-column>
				<el-table-column prop="phone" label="手机号" show-overflow-tooltip></el-table-column>
				<el-table-column prop="email" label="邮箱" show-overflow-tooltip></el-table-column>
				<el-table-column prop="status" label="用户状态" show-overflow-tooltip>
					<template #default="scope">
						<el-tag type="success" v-if="scope.row.status">启用</el-tag>
						<el-tag type="info" v-else>禁用</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="remark" label="备注" show-overflow-tooltip></el-table-column>
				<el-table-column prop="createTime" label="创建时间" show-overflow-tooltip></el-table-column>
				<el-table-column label="操作" width="100">
					<template #default="scope">
						<el-button :disabled="scope.row.userName === 'admin'" size="small" text type="primary" @click="onOpenEditUser('edit', scope.row)"
							>修改</el-button
						>
						<el-button :disabled="scope.row.userName === 'admin'" size="small" text type="primary" @click="onRowDel(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="onHandleSizeChange"
				@current-change="onHandleCurrentChange"
				class="mt15"
				:pager-count="5"
				:page-sizes="[10, 20, 30]"
				v-model:current-page="state.tableParams.pageNum"
				background
				v-model:page-size="state.tableParams.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.tableParams.totalNum"
			>
			</el-pagination>
		</el-card>
		<UserDialog ref="userDialogRef" :orgData="state.orgTreeData" @handleQuery="handleQuery()" />
	</div>
</template>

<script setup lang="ts" name="systemUser">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { getAPI } from '/@/axios-utils';
import { SysUserApi,SysOrgApi } from '/@/api-services/api';
import { SysUser,SysOrg } from '/@/api-services/models';

// 引入组件
const UserDialog = defineAsyncComponent(() => import('/@/views/system/user/dialog.vue'));

// 定义变量内容
const userDialogRef = ref();
const state = reactive({
	loading: false,
	userData: [] as Array<SysUser>,
	orgTreeData: [] as Array<SysOrg>,
	queryParams: {
		// orgId: -1,
		// account: undefined,
		realName: undefined,
		// phone: undefined,
	},
	tableParams: {
		pageNum: 1,
		pageSize: 10,
		totalNum: 0 as any,
		totalPage: 0 as any,
		sort: '1',
		sortType: 'ascending',
	},
});

// 查询操作
const handleQuery = async () => {
	state.loading = true;
	let params = Object.assign(state.queryParams, state.tableParams);
	var res = await getAPI(SysUserApi).apiSysUserControllerPagePost(params);
	state.userData = res.data.result?.result ?? [];
	state.tableParams.totalNum = res.data.result?.totalNum;
	state.loading = false;
};

// 打开新增用户弹窗
const onOpenAddUser = (type: string) => {
	userDialogRef.value.openDialog(type);
};
// 打开修改用户弹窗
const onOpenEditUser = (type: string, row: RowUserType) => {
	userDialogRef.value.openDialog(type, row);
};
// 删除用户
const onRowDel = (row: any) => {
	ElMessageBox.confirm(`此操作将永久删除账户名称：“${row.userName}”，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await getAPI(SysUserApi).apiSysUserControllerDeleteUserPost({ id: row.id })
			handleQuery();
			ElMessage.success('删除成功');
		})
		.catch(() => {});
};

// 分页改变
const onHandleSizeChange = (val: number) => {
	state.tableParams.pageSize = val;
	handleQuery();
};

// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.tableParams.pageNum = val;
	handleQuery();
};

// 查询机构数据
const loadOrgData = async () => {
	state.loading = true;
	var res = await getAPI(SysOrgApi).apiSysOrgControllerGetListGet(0);
	state.orgTreeData = res.data.result ?? [];
	state.loading = false;
};

// 页面加载时
onMounted(() => {
	loadOrgData();
	handleQuery();
});

/**
 * 格式化显示
 * @param cellValue 
 */
const dictFormatter = (cellValue: any) => {
	if (cellValue != null) {
		return FindSysOrg(state.orgTreeData,cellValue);
	}
};

const FindSysOrg = ( children: Array<SysOrg>,cellValue: string | null | undefined) =>{
	for (let index = 0; index < children.length; index++) {
		if(children[index].code == cellValue){
			return children[index].name;
		}
		else if(children[index].children != null && children[index].children != undefined ){
			let name = FindSysOrg(children[index].children,cellValue);
			if(name != null){
				return name;
			}
			
		}
	}
	return null;
}
</script>

<style scoped lang="scss">
.system-user-container {
	:deep(.el-card__body) {
		display: flex;
		flex-direction: column;
		flex: 1;
		overflow: auto;
		.el-table {
			flex: 1;
		}
	}
}
</style>
